//
//  BSLPhotosViewController.m
//  Demo
//
//  Created by RYAN on 15/6/26.
//
//

#import "BSLPhotosViewController.h"
#import "BSLPhotoCollectionViewCell.h"
#import "BSLGalleryPlugin.h"
#import "BSLGalleryHelper.h"
#import "BSLAsset.h"
#import "BSLRevealViewController.h"

#define CELL_PADDING 2.13
#define MAX_SELECT 9

@interface BSLPhotosViewController ()

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSMutableArray *assets;
@property (nonatomic, strong) NSMutableArray *selectedAssets;

@property (nonatomic, strong) UIButton *doneBtn;

@end

@implementation BSLPhotosViewController

- (id)initWithGroup:(ALAssetsGroup *)group{
    self = [super init];
    if (self) {
        self.currentGroup = group;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setFrame:SCREEN_FRAME];
    
    NSMutableArray *temp = [NSMutableArray array];
    self.assets = temp;
    
    [self setupCollectionView];
    [self setupToolBar];
    [self setupNav];
    
    [self performSelectorInBackground:@selector(loadAssets) withObject:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setToolbarHidden:NO];
    [self.navigationController setNavigationBarHidden:NO];
    
    BOOL isChanged;
    NSMutableArray *array = [NSMutableArray array];
    for (int i=0; i<self.selectedAssets.count; i++){
        BSLAsset *asset = [self.selectedAssets objectAtIndex:i];
        if (asset.isUserChosen) {
            [array addObject:asset];
            isChanged = YES;
        }
    }
    
    if (isChanged) {
        self.selectedAssets = array;
        [self.collectionView reloadData];
        [self updateBtnTitle];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma ToolBar
- (void)setupToolBar{
    NSMutableArray *items = [NSMutableArray arrayWithCapacity:4];
    
    UIBarButtonItem *item0 = [[UIBarButtonItem alloc] initWithTitle:@"预览" style:UIBarButtonItemStylePlain target:self action:@selector(preview)];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:NULL];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundColor:[UIColor colorWithRed:225/255.0 green:62/255.0 blue:62/255.0 alpha:1]];
    [button setAdjustsImageWhenHighlighted:NO];
    [button setFrame:CGRectMake(0, 0, 55, 30)];
    button.layer.cornerRadius = 15;
    button.clipsToBounds = YES;
    [button setTitle:@"0" forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15]];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -32, 0, 0)];
    [button setImage:[UIImage imageNamed:@"btnDone"] forState:UIControlStateNormal];
    [button setImageEdgeInsets:UIEdgeInsetsMake(1, 32, 0, 0)];
    [button addTarget:self action:@selector(finishPicking:) forControlEvents:UIControlEventTouchUpInside];
    self.doneBtn = button;
    UIBarButtonItem *item2 =[[UIBarButtonItem alloc] initWithCustomView:self.doneBtn];
    
    [items addObject:item0];
    [items addObject:item1];
    [items addObject:item2];
    
    [self setToolbarItems:items];
}

- (void)updateBtnTitle{
    NSString *titleString = [NSString stringWithFormat:@"%lu",(unsigned long)self.selectedAssets.count];
    [self.doneBtn setTitle:titleString forState:UIControlStateNormal];
}

- (void)preview{
    
    if (!self.selectedAssets || self.selectedAssets.count == 0) {
        return;
    }
    
    BSLRevealViewController *revealVC = [[BSLRevealViewController alloc] initWithAssets:self.selectedAssets];
//    [self.navigationController setNavigationBarHidden:YES];
    [self.navigationController pushViewController:revealVC animated:[BSLGalleryHelper shareInatance].isAnimated];
}

- (void)finishPicking:(UIButton *)btn{
//    NSLog(@"%@",self.selectedAssets);
//    if (self.selectedAssets.count == 0) {
//        return;
//    }

    NSMutableArray *libraryPaths = [[BSLGalleryHelper shareInatance] saveToLibrary:self.selectedAssets];
    NSString *errorMessage = nil;
    
    if (!libraryPaths || libraryPaths.count == 0) {
        errorMessage = @"select no images";
    }
    
    [(GalleryNavigationController *)self.navigationController dismiss:libraryPaths errorMessage:errorMessage];
}

#pragma Nav
- (void)setupNav{
    self.title = [self.currentGroup valueForProperty:ALAssetsGroupPropertyName];
    
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]
                                 initWithTitle:@"取消"
                                 style:UIBarButtonItemStylePlain
                                 target:self
                                 action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem = rightBtn;
    
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc]
                                 initWithTitle:@"返回"
                                 style:UIBarButtonItemStylePlain
                                 target:self
                                 action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftBtn;
}

- (void)cancel{
    [(GalleryNavigationController *)self.navigationController dismiss:nil errorMessage:@"select no images"];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:[BSLGalleryHelper shareInatance].isAnimated];
}

#pragma Load Data
- (void)loadAssets{

    [self.assets removeAllObjects];
    [self.currentGroup enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if (result) {
            //派生ALAsset
            BSLAsset *asset = [[BSLAsset alloc] initWithAsset:result];
            [self.assets addObject:asset];
        }

        else{
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
                
            });
        }
    }];
}

#pragma UICollectionView
- (void)setupCollectionView{
    
    CGFloat itemWidth = (self.view.bounds.size.width - CELL_PADDING*3)/4.0;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [layout setItemSize:CGSizeMake(itemWidth, itemWidth)];
    [layout setMinimumInteritemSpacing:CELL_PADDING];
    [layout setMinimumLineSpacing:CELL_PADDING];
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    [self.collectionView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.collectionView];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.bounces = YES;
    [self.collectionView registerClass:[BSLPhotoCollectionViewCell class] forCellWithReuseIdentifier:@"BSLPhotoCollectionViewCell"];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma UICollectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.assets.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BSLPhotoCollectionViewCell *cell = (BSLPhotoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"BSLPhotoCollectionViewCell" forIndexPath:indexPath];
    NSInteger index = indexPath.item;
    
    BSLAsset *asset = [self.assets objectAtIndex:index];
    [cell setDataWithAsset:asset];
    [cell setStatus:asset.isUserChosen];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.selectedAssets) {
        self.selectedAssets = [NSMutableArray array];
    }
    
    BSLPhotoCollectionViewCell *currentCell = (BSLPhotoCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    if (MAX_SELECT > self.selectedAssets.count) {

        BSLAsset *asset = [self.assets objectAtIndex:indexPath.item];
        asset.isUserChosen = !asset.isUserChosen;
        
        if (asset.isUserChosen) {
            [self.selectedAssets addObject:asset];
        }
        
        else{
            [self.selectedAssets removeObject   :asset];
        }
        
        [currentCell setStatus:asset.isUserChosen];
        [self updateBtnTitle];
    }
    
    else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"不能超过%d张",MAX_SELECT] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
    }
}

@end
